package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
    //专门处理重复键异常
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        //记录异常信息
        log.error(e.getMessage());
        //获取异常信息并返回友好的错误提示
        String message = e.getMessage();
        int index = message.indexOf("Duplicate entry");
        String errorMsg = message.substring(index);
        String[] split = errorMsg.split(" ");
        return Result.error( split[2] + MessageConstant.ALREADY_EXISTS);
    }

}
